import { useState, useEffect } from 'react';
import { Card, Button, Form, Input, message, Modal } from 'antd';
import {
    SettingOutlined, CheckOutlined, ExclamationCircleOutlined,
    AlignCenterOutlined
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';

import { updateSerial, updateIp, buildstore } from "@/api/config"
import { getState } from "@/api/common"
import './index.scss';

// 提取常量
const INITIAL_INFO = {
    "ad_serial": "",
    "ipconfig": { "post": "", "ip": "", "cid": "" },
    "cid": "", "ip": "", "post": "", "msg": "",
    "serial_state": "", "state": "", "version": ""
};

function Config(props) {
    const { t } = useTranslation();
    const [form] = Form.useForm();
    const [form2] = Form.useForm();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [info, setInfo] = useState(INITIAL_INFO);

    // 提取重复的卡片标题渲染
    const renderCardTitle = (icon, titleKey) => (
        <div className='title'>
            {icon}
            <span className="tit">{t(titleKey)}</span>
        </div>
    );

    // 提取运行状态显示
    const renderRunningStatus = () => {
        if (info.state === 'on') return <span className='txt'>{t('header.running')}</span>;
        if (info.state === 'off') return <span className='txt error'>{t('header.stopped')}</span>;
        return <span className='txt'>{t('header.unknown')}</span>;
    };

    function getLoad() {
        getState().then(res => {
            setInfo(res[0]);
        });
    }

    function onFinish(values) {
        updateIp(values).then(res => {
            message.success(t('config.saveSuccess'));
            getLoad();
        })
    }

    function onFinish2(values) {
        updateSerial(values).then(res => {
            message.success(t('config.saveSuccess'));
            getLoad();
        })
    }

    function submit() {
        buildstore().then(res => {
            cancel();
            message.success(res.msg);
        })
    }

    function cancel() {
        setIsModalOpen(false);
    }

    function onReset() {
        form.resetFields();
    }

    function onReset2() {
        form2.resetFields();
    }
    function str(str){
        return str.split(",").pop();
    }
    useEffect(() => {
        getLoad();
    }, [])

    return (
        <div className="config-container">
            <div className="row-a1">
                <div className="left">
                    {/* 服务器配置 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<SettingOutlined style={{ color: '#08c' }} />, 'config.serverConfig')}>
                            <Form
                                form={form}
                                layout="vertical"
                                autoComplete="off"
                                onFinish={onFinish}
                            >
                                <Form.Item
                                    label={t('config.serverAddress')}
                                    name="ip"
                                    rules={[{
                                        required: true,
                                        message: t('config.inputServerAddress'),
                                    }]}
                                >
                                    <Input />
                                </Form.Item>
                                <Form.Item
                                    label={t('config.shelfSerialNumber')}
                                    name="cid"
                                    rules={[{
                                        required: true,
                                        message: t('config.inputShelfSerialNumber'),
                                    }]}
                                >
                                    <Input />
                                </Form.Item>
                                <Form.Item>
                                    <div className="btns">
                                        <Button className='submit-btn btn' icon={<CheckOutlined />} type="primary" htmlType="submit">
                                            {t('config.saveConfig')}
                                        </Button>
                                        <Button className='reset-btn btn' type="primary" onClick={onReset}>
                                            {t('config.reset')}
                                        </Button>
                                    </div>
                                </Form.Item>
                            </Form>
                        </Card>
                    </div>

                    {/* 串口地址配置 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<SettingOutlined style={{ color: '#08c' }} />, 'config.serialAddressConfig')}>
                            <Form
                                form={form2}
                                layout="vertical"
                                autoComplete="off"
                                onFinish={onFinish2}
                            >
                                <Form.Item
                                    label={t('config.address')}
                                    name="addrs"
                                    rules={[{
                                        required: true,
                                        message: t('config.inputAddress'),
                                    }]}
                                >
                                    <Input />
                                </Form.Item>
                                <Form.Item>
                                    <div className="btns">
                                        <Button className='submit-btn btn' icon={<CheckOutlined />} type="primary" htmlType="submit">
                                            {t('config.saveConfig')}
                                        </Button>
                                        <Button className='reset-btn btn' type="primary" onClick={onReset2}>
                                            {t('config.reset')}
                                        </Button>
                                    </div>
                                </Form.Item>
                            </Form>
                        </Card>
                    </div>

                    {/* 重建位置 */}
                    <div className="con-a2">
                        <Card title={renderCardTitle(<AlignCenterOutlined style={{ color: '#08c' }} />, 'config.dr')}>
                            <div className="btns">
                                <Button className='submit-btn' onClick={() => setIsModalOpen(true)} type="primary">
                                    {t('config.rebuildLocation')}
                                </Button>
                            </div>
                        </Card>
                    </div>
                </div>

                <div className="right">
                    <div className="con-a3">
                        <Card title={renderCardTitle(<ExclamationCircleOutlined style={{ color: '#08c' }} />, 'config.configInfo')}>
                            <div className="info">
                                <div className="icon">
                                    <ExclamationCircleOutlined style={{ color: '#0c5460' }} />
                                </div>
                                <div className="text">
                                    <div className="txt">
                                        <span className='tit'>{t('common.runningStatus')}：</span>
                                        <span className='in'>{renderRunningStatus()}</span>
                                    </div>
                                    <div className="txt">
                                        <span className='tit'>{t('config.softwareVersion')}：</span>
                                        <span className='in'>{info.version}</span>
                                    </div>
                                </div>
                            </div>
                            <div className="list">
                                <div className="li">
                                    <div className="tit">{t('config.serverAddr')}</div>
                                    <div className="text">
                                        <div className="txt">{info.ipconfig.ip}</div>
                                    </div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t('config.shelfSerial')}</div>
                                    <div className="text">
                                        <div className="txt">{info.ipconfig.cid}</div>
                                    </div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t('config.address')}</div>
                                    <div className="text">
                                        <div className="txt">{str(info.ad_serial)}</div>
                                    </div>
                                </div>
                            </div>
                        </Card>
                    </div>
                </div>
            </div>

            <Modal
                title={t('config.prompt')}
                cancelText={t('config.cancel')}
                okText={t('config.confirm')}
                open={isModalOpen}
                onOk={submit}
                onCancel={cancel}
            >
                <div>{t('config.caution')}</div>
            </Modal>
        </div>
    );
}

export default Config;